<!DOCTYPE html><html class="appearance-auto" lang="zh-CN"><head><meta charset="UTF-8"><title>【Spring源码解析系列】 Aware</title><meta name="description" content="用创业者心态做好每一件事情！"><meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no, initial-scale=1"><!-- Google Analytics --><!-- End Google Analytics -->
<!-- Baidu Analytics --><!-- End Baidu Analytics --><link rel="icon" href="/blog/images/favicon.png"><link rel="stylesheet" href="/blog/style/common/bulma.css"><link rel="stylesheet" href="/blog/style/base.css"><link rel="stylesheet" href="/blog/style/common/helper.css"><script src="/blog/js/common.js"></script><link rel="stylesheet" href="/blog/style/post.css"><link rel="stylesheet" href="/blog/style/themes/highlight-theme-light.css"><script src="/blog/js/highlight.pack.js"></script><meta name="description" content="
本文主要讲述Spring中Aware的用法以及实现


Aware意义在Spring当中有一些内置的对象是未开放给我们使用的，例如Spring的上下文ApplicationContext、环境属性Environment、BeanFactory等等其它的一些内置对象，而在我们可以通过实现对应的Aware接口去拿到我们想要的一些属性，一般命名都是xxxAware，在创建对象的时候，会调用接口规定的方法注入到相关组件：Aware

示例@Component
public class MyEnvironmentAware implements EnvironmentAware &amp;#123;

    @Override
    public void setEnvironment(Environment envi.."><!-- hexo injector head_end start -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.12.0/dist/katex.min.css">

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hexo-math@4.0.0/dist/style.css">
<!-- hexo injector head_end end --><meta name="generator" content="Hexo 5.4.1"><link rel="alternate" href="/blog/atom.xml" title="janedler's blog" type="application/atom+xml">
</head><body class="is-flex is-flex-direction-column"><header class="header-widget is-flex-shrink-0 is-hidden-mobile"><div class="container is-fullhd is-flex is-justify-content-space-between is-align-items-center is-full-height"><section class="is-hidden-mobile is-flex-shrink-0"><h2><a href="/blog/">田园牧歌(*︶*)'s blog</a></h2></section><h3 class="is-hidden-mobile is-family-serif is-full-height is-flex is-align-items-center is-flex-shrink-0"><div class="is-full-height" id="postTopic"><p class="is-full-height is-flex-shrink-0 is-flex is-align-items-center is-justify-content-center">【Spring源码解析系列】 Aware</p><p class="is-full-height is-flex-shrink-0 is-flex is-align-items-center is-justify-content-center">点击返回顶部</p></div></h3><aside class="is-flex-shrink-0"><h3 class="is-inline-block"><a href="/blog/">首页</a></h3><h3 class="is-inline-block"><a href="/blog/about">关于</a></h3><h3 class="is-inline-block"><a href="/blog/archives">归档</a></h3></aside></div></header><header class="is-flex header-widget is-flex-shrink-0 is-align-items-center is-justify-content-center is-hidden-tablet"><h3 class="is-inline-block"><a href="/blog/">首页</a></h3><h3 class="is-inline-block"><a href="/blog/about">关于</a></h3><h3 class="is-inline-block"><a href="/blog/archives">归档</a></h3></header><main><main class="container is-max-widescreen content section post-page pt-4 px-4"><div class="columns is-flex-desktop is-justify-content-center is-flex-direction-row-reverse"><div class="column is-3 is-hidden-mobile"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#Aware%E6%84%8F%E4%B9%89"><span class="toc-text">Aware意义</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%A4%BA%E4%BE%8B"><span class="toc-text">示例</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90"><span class="toc-text">源码解析</span></a></li></ol></div><div class="column is-9"><header class="my-4"><a href="/blog/tags/Java"><i class="tag post-item-tag">Java</i></a><a href="/blog/tags/Spring"><i class="tag post-item-tag">Spring</i></a></header><h1 class="mt-0 mb-1 is-family-serif" id="postTitle">【Spring源码解析系列】 Aware</h1><time class="has-text-grey" datetime="2022-11-30T16:00:00.000Z">2022-12-01</time><article class="mt-2 post-content"><p><img src="https://janedler.oss-cn-beijing.aliyuncs.com/images/spring.png" alt="cover"></p>
<p>本文主要讲述Spring中Aware的用法以及实现</p>
<span id="more"></span>

<h2 id="Aware意义"><a href="#Aware意义" class="headerlink" title="Aware意义"></a>Aware意义</h2><p>在Spring当中有一些内置的对象是未开放给我们使用的，例如Spring的上下文ApplicationContext、环境属性Environment、BeanFactory等等其它的一些内置对象，而在我们可以通过实现对应的Aware接口去拿到我们想要的一些属性，一般命名都是xxxAware，在创建对象的时候，会调用接口规定的方法注入到相关组件：Aware</p>
<p><img src="https://janedler.oss-cn-beijing.aliyuncs.com/images/202212011102922.png" alt="image-20221201110246855"></p>
<h2 id="示例"><a href="#示例" class="headerlink" title="示例"></a>示例</h2><pre><code class="java">@Component
public class MyEnvironmentAware implements EnvironmentAware &#123;

    @Override
    public void setEnvironment(Environment environment) &#123;
        System.out.println(&quot;MyEnvironmentAware: &quot; + environment.toString());
    &#125;
&#125;
</code></pre>
<pre><code class="bash">MyEnvironmentAware: StandardEnvironment &#123;activeProfiles=[], defaultProfiles=[default], propertySources=[MapPropertySource &#123;name=&#39;systemProperties&#39;&#125;, SystemEnvironmentPropertySource &#123;name=&#39;systemEnvironment&#39;&#125;]&#125;
MyEnvironmentAware: StandardEnvironment &#123;activeProfiles=[], defaultProfiles=[default], propertySources=[MapPropertySource &#123;name=&#39;systemProperties&#39;&#125;, SystemEnvironmentPropertySource &#123;name=&#39;systemEnvironment&#39;&#125;]&#125;
</code></pre>
<h2 id="源码解析"><a href="#源码解析" class="headerlink" title="源码解析"></a>源码解析</h2><pre><code class="java">class ApplicationContextAwareProcessor implements BeanPostProcessor &#123;
    private final ConfigurableApplicationContext applicationContext;

    private final StringValueResolver embeddedValueResolver;
    /**
     * Create a new ApplicationContextAwareProcessor for the given context.
     */
    public ApplicationContextAwareProcessor(ConfigurableApplicationContext applicationContext) &#123;
        this.applicationContext = applicationContext;
        this.embeddedValueResolver = new EmbeddedValueResolver(applicationContext.getBeanFactory());
    &#125;
    @Override
    @Nullable
    public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException &#123;
        AccessControlContext acc = null;

        if (System.getSecurityManager() != null &amp;&amp;
                (bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
                        bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
                        bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)) &#123;
            acc = this.applicationContext.getBeanFactory().getAccessControlContext();
        &#125;

        if (acc != null) &#123;
            AccessController.doPrivileged((PrivilegedAction&lt;Object&gt;) () -&gt; &#123;
                invokeAwareInterfaces(bean);
                return null;
            &#125;, acc);
        &#125;
        else &#123;
            invokeAwareInterfaces(bean);
        &#125;

        return bean;
    &#125;

    private void invokeAwareInterfaces(Object bean) &#123;
        // 判断是否实现了各个 Aware 接口
        if (bean instanceof Aware) &#123;
            if (bean instanceof EnvironmentAware) &#123;
                ((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
            &#125;
            if (bean instanceof EmbeddedValueResolverAware) &#123;
                ((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
            &#125;
            if (bean instanceof ResourceLoaderAware) &#123;
                ((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
            &#125;
            if (bean instanceof ApplicationEventPublisherAware) &#123;
                ((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
            &#125;
            if (bean instanceof MessageSourceAware) &#123;
                ((MessageSourceAware) bean).setMessageSource(this.applicationContext);
            &#125;
            if (bean instanceof ApplicationContextAware) &#123;
                ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
            &#125;
        &#125;
    &#125;

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) &#123;
        return bean;
    &#125;
&#125;
</code></pre>
<p>比如实现EnvironmentAware接口的bean在该Processor内会调用EnvironmentAware接口的setEnvironment方法，并把spring容器内部的ConfigurableEnvironment传递进去。一般最常用的就是bean实现ApplicationContextAware接口，这样ApplicationContextAwareProcessor就会将ApplicationContext设置到该bean里。</p>
</article><section class="jump-container is-flex is-justify-content-space-between my-6"><!-- em is empty placeholder--><a class="button is-default" href="/blog/2022/12/10/Spring/Spring-AOP%E5%88%9D%E4%BD%93%E9%AA%8C/" title="【Spring源码解析系列】 AOP初体验"><i class="iconfont icon-prev mr-2 has-text-grey"></i><span class="has-text-weight-semibold">上一页: 【Spring源码解析系列】 AOP初体验</span></a><a class="button is-default" href="/blog/2022/12/01/Spring/Spring-AOP%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90/" title="【Spring源码解析系列】 AOP源码解析"><span class="has-text-weight-semibold">下一页: 【Spring源码解析系列】 AOP源码解析</span><i class="iconfont icon-next ml-2 has-text-grey"></i></a></section><article class="mt-6 comment-container"><script async repo="janedler/blog" src="https://utteranc.es/client.js" issue-term="pathname" theme="preferred-color-scheme"></script></article></div></div></main></main><footer class="is-flex is-flex-direction-column is-align-items-center is-flex-shrink-0 is-family-serif"><section class="sns-container"><!-- Github--><a title="github" target="_blank" rel="noopener nofollow" href="//github.com//janedler"><i class="iconfont icon-github"></i></a><!-- Ins--><!-- RSS--><a title="rss" target="_blank" rel="noopener nofollow" href="/blog/atom.xml"><i class="iconfont icon-rss"></i></a><!-- 知乎--><!-- 领英--><!-- 脸书--></section><p><span>Copyright ©</span><span> 田园牧歌(*︶*) 2022</span></p><div class="is-flex is-justify-content-center is-flex-wrap-wrap"><p>Powered by Hexo &verbar;&nbsp;</p><p class="is-flex is-justify-content-center"><a title="Hexo theme author" target="_blank" rel="noopener" href="//github.com/haojen">Theme by Haojen&nbsp;</a></p><div style="margin-top: 2px"><a class="github-button" title="github-button" target="_blank" rel="noopener" href="https://github.com/haojen/hexo-theme-Claudia" data-color-scheme="no-preference: light; light: light; dark: dark;" data-show-count="true"></a></div></div><div><span></span></div></footer><script async defer src="https://buttons.github.io/buttons.js"></script><script src="/blog/js/post.js"></script></body></html>